/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package httpserver;

import httpserver.connections.ShutdownWorker;
import httpserver.users.User;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 *
 * @author Bryce
 */
public class HttpServer {

    private static final int PORT_DEFAULT = 7033;
    public static ArrayList<User> users;
    public static ServerSocket listeningSocket;
    public static ShutdownWorker shutdownWorker;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        //initialize
        users = new ArrayList<User>();
        //Hook in the system shutdown listener to close ports etc..
        shutdownWorker = new ShutdownWorker(users,listeningSocket);
        Thread hook = new Thread(shutdownWorker);
        Runtime.getRuntime().addShutdownHook(hook);
        
        //Start listening
        String listenPortDisplay;
        int listenPort;
        if (args.length > 0) {
            listenPortDisplay = args[0];
            try {
                listenPort = Integer.parseInt(listenPortDisplay);
            } catch (NumberFormatException nfe) {
                System.out.println("SEVERE: Failed to parse port.");
                return;
            }
        } else {
            listenPort = PORT_DEFAULT;
        }

        listeningSocket = new ServerSocket(listenPort);
        System.out.println("Listening for incomming connection on: " + listeningSocket.getLocalPort());

        //go in a infinite loop, wait for connections, process request, send response
        int userCounter = 0;
        while (true) {
            System.out.println("\nReady, Waiting for requests...\n");
            try {
                //this call waits/blocks until someone connects to the port we
                //are listening to
                Socket connectionsocket = listeningSocket.accept();
                //Create a user object with this newly connected socket.
                User user = new User(connectionsocket);
                Thread thread = new Thread(user,"User-"+userCounter);
                thread.run();
                users.add(userCounter,user);
                userCounter++;
                
            } catch (Exception e) { //catch any errors, and print them
                System.out.println("\nError:\n" + e);
                e.printStackTrace(System.out);
            }

        } //go back in loop, wait for next request
    }
    
}
